<?php

namespace app\admin\controller;

use think\App;
use think\Request;

class Article extends Common
{
    protected $db;

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->db = new \app\common\model\Articles();
    }

    /**
     * 栏目管理首页
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list  = $this->db->order('id','desc')-> paginate(10);
        $this->assign('list_tag', $list);
        return $this->fetch();
    }

    /**
     * 添加文章
     *
     * @param Request $request
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(Request $request)
    {
        if ($request->isPost()) {
            $post = $request->param();
            $res = $this->db->add($post);
            if ($res['code']) {
                $this->success($res['message'], 'index');
            } else {
                $this->error($res['message']);
            }
        }
        $cate=(new \app\common\model\Category())->getAll();
        $tag = db('tag')->select();
        $this->assign('cate', $cate);
        $this->assign('tag', $tag);
        return $this->fetch();
    }

    /**
     * 标签编辑
     *
     * @param Request $request
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $post = $request->param();
            $results = $this->db->edit($post);
            if ($results['code']) {
                $this->success($results['message'], 'index');
            } else {
                $this->error($results['message']);
            }
        }
        $id = $request->param('id');
        $res = $this->db->where('id', $id)->find();
        $this->assign('info', $res);
        return $this->fetch();
    }

    /**
     * @param Request $request
     *
     * @return mixed
     * @throws \Exception
     */
    public function delete(Request $request)
    {
        $id = $request->param('id');
        $res = $this->db->where('id', $id)->delete();
        if (!$res) {
            $this->error('标签删除失败');
        }
        $this->success('标签删除成功', 'index');
    }
}